SPB Git

Repository Public

route.ts 4.7 KB 88 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : ORIX App Universe8 * File             : src/app/download/[slug]/[version]/[file]/route.ts9 * Module           : app10 * Repository       : https://git.spboucher.ai/orix-spboucher-ai11 * Project Website  : https://www.orixlab.dev12 * Created          : 2026-11-2113 * Last Modified    : 2026-11-2114 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243import { createReadStream } from "node:fs";44import { stat } from "node:fs/promises";45import { Readable } from "node:stream";46import { getApp } from "@/lib/catalog";47import { count } from "@/lib/downloads/metrics";48import { publishedArtifacts } from "@/lib/releases/store";49import { clientIp } from "@/lib/security/http";50import { rateLimit } from "@/lib/security/ratelimit";5152export const dynamic = "force-dynamic";5354const notFound = () => new Response("Not found", { status: 404, headers: { "Cache-Control": "no-store", "X-Robots-Tag": "noindex" } });5556/**57 * Serves one thing only: an image an administrator approved, whose checksum this server verified, belonging to a58 * published application. The path on disk comes from the database row, never from the request, so the route59 * cannot be turned into a file or repository proxy.60 */61export async function GET(req: Request, { params }: { params: Promise<{ slug: string; version: string; file: string }> }) {62  const { slug, version, file } = await params;63  try { rateLimit("download", clientIp(req), 20, 60); } catch { return new Response("Too many requests", { status: 429, headers: { "Retry-After": "60" } }); }64  if (!getApp(slug)) return notFound();65  const rel = publishedArtifacts(slug).find((r) => (r.version ?? r.tag) === version && r.asset_name === file);66  if (!rel?.artifact) return notFound();67  const st = await stat(rel.artifact).catch(() => null);68  if (!st?.isFile() || (rel.asset_size !== null && st.size !== rel.asset_size)) return notFound(); // never serve a file that no longer matches what was verified6970  const headers: Record<string, string> = {71    "Content-Type": "application/x-apple-diskimage", "Content-Disposition": `attachment; filename="${rel.asset_name.replace(/[^A-Za-z0-9 ._+()-]/g, "_")}"`,72    "Accept-Ranges": "bytes", ETag: `"${rel.sha256_computed}"`, "Cache-Control": "public, max-age=3600, immutable", "X-Content-Type-Options": "nosniff", "X-Robots-Tag": "noindex",73    "X-Checksum-Sha256": rel.sha256_computed ?? "",74  };75  const range = /^bytes=(\d*)-(\d*)$/.exec(req.headers.get("range") ?? "");76  if (range && (range[1] || range[2])) {77    const start = range[1] ? Number(range[1]) : Math.max(0, st.size - Number(range[2]));78    const end = range[1] && range[2] ? Math.min(Number(range[2]), st.size - 1) : st.size - 1;79    if (start > end || start >= st.size) return new Response(null, { status: 416, headers: { "Content-Range": `bytes */${st.size}` } });80    return new Response(Readable.toWeb(createReadStream(rel.artifact, { start, end })) as ReadableStream, { status: 206, headers: { ...headers, "Content-Length": String(end - start + 1), "Content-Range": `bytes ${start}-${end}/${st.size}` } });81  }82  count("request", slug, version);83  const stream = createReadStream(rel.artifact);84  // "completed" = the server sent the last byte. It says nothing about what happened on the visitor's side.85  stream.on("end", () => { try { count("completed", slug, version); } catch { /* counters are best-effort */ } });86  return new Response(Readable.toWeb(stream) as ReadableStream, { headers: { ...headers, "Content-Length": String(st.size) } });87}88
Files main
Menu

Theme